﻿using furion.blog.Domain.MySQL;
using Furion;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Web.Core
{
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(
            this IServiceCollection services, 
            IConfiguration configuration, 
            string dbName = "db_master")
        {
            //如果多个数数据库传 List<ConnectionConfig>
            string conn = App.Configuration["MySQL"];

            var configConnection = new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.MySql,
                ConnectionString = conn,
                IsAutoCloseConnection = true,
            };

            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
                db =>
                {
                    //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            Console.WriteLine(sql);//输出sql

                            string path = @"\logs\sql.txt";
                            if (!File.Exists(path))
                            {
                                File.Create(path).Close();
                            }
                            using (StreamWriter writer = File.AppendText(path))
                            {
                                writer.WriteLine(sql);
                                writer.Flush();//刷新缓存
                                writer.Close();
                                writer.Dispose();
                            }

                        };
                });

            sqlSugar.CodeFirst.SplitTables().InitTables<RequestLog>();
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }
}
